package jnpf.base.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jnpf.base.controller.SuperController;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jnpf.base.ActionResult;
import jnpf.base.Page;
import jnpf.base.entity.SystemEntity;
import jnpf.base.model.base.SystemCrModel;
import jnpf.base.model.base.SystemListVO;
import jnpf.base.model.base.SystemPageVO;
import jnpf.base.model.base.SystemVO;
import jnpf.base.service.CommonWordsService;
import jnpf.base.service.SystemService;
import jnpf.base.vo.ListVO;
import jnpf.constant.MsgCode;
import jnpf.message.util.OnlineUserModel;
import jnpf.message.util.OnlineUserProvider;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.service.UserService;
import jnpf.util.JsonUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统控制器
 *
 * @author ：JNPF开发平台组
 * @version: V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date ：2022/6/21 15:33
 */
@Tag(name = "系统", description = "system")
@RestController
@RequestMapping("/api/system/System")
public class SystemController extends SuperController<SystemService, SystemEntity> {

    @Autowired
    private SystemService systemService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private CommonWordsService commonWordsService;

    /**
     * 获取系统列表
     *
     * @param page 关键字
     * @return ignore
     */
    @Operation(summary = "获取系统列表")
    @SaCheckPermission("system.menu")
    @GetMapping
    public ActionResult<ListVO<SystemListVO>> list(SystemPageVO page) {
        List<SystemEntity> list = systemService.getList(page.getKeyword(),
                page.getEnableMark() != null && page.getEnableMark().equals("1"));
        List<SystemListVO> jsonToList = JsonUtil.getJsonToList(list, SystemListVO.class);
        return ActionResult.success(new ListVO<>(jsonToList));
    }

    /**
     * 获取系统详情
     *
     * @param id 主键
     * @return ignore
     */
    @Operation(summary = "获取系统详情")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @SaCheckPermission("system.menu")
    @GetMapping("/{id}")
    public ActionResult<SystemVO> info(@PathVariable("id") String id) {
        SystemEntity entity = systemService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail(MsgCode.FA001.get());
        }
        SystemVO jsonToBean = JsonUtil.getJsonToBean(entity, SystemVO.class);
        return ActionResult.success(jsonToBean);
    }

    /**
     * 新建系统
     *
     * @param systemCrModel 新建模型
     * @return ignore
     */
    @Operation(summary = "新建系统")
    @Parameters({
            @Parameter(name = "systemCrModel", description = "新建模型", required = true)
    })
    @SaCheckPermission("system.menu")
    @PostMapping
    public ActionResult create(@RequestBody SystemCrModel systemCrModel) {
        SystemEntity entity = JsonUtil.getJsonToBean(systemCrModel, SystemEntity.class);
        if (systemService.isExistFullName(entity.getId(), entity.getFullName())) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (systemService.isExistEnCode(entity.getId(), entity.getEnCode())) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        systemService.create(entity);
        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 修改系统
     *
     * @param id 主键
     * @param systemCrModel 修改模型
     * @return ignore
     */
    @Operation(summary = "修改系统")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
            @Parameter(name = "systemCrModel", description = "修改模型", required = true)
    })
    @SaCheckPermission("system.menu")
    @PutMapping("/{id}")
    public ActionResult update(@PathVariable("id") String id, @RequestBody SystemCrModel systemCrModel) {
        SystemEntity systemEntity = systemService.getInfo(id);
        if (systemEntity == null) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        // 主系统不允许禁用
        if (systemEntity.getIsMain() == 1 && systemCrModel.getEnabledMark() == 0) {
            return ActionResult.fail("更新失败，主系统不允许禁用");
        }
        SystemEntity entity = JsonUtil.getJsonToBean(systemCrModel, SystemEntity.class);
        entity.setIsMain(systemEntity.getIsMain());
        if (systemService.isExistFullName(id, entity.getFullName())) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (systemService.isExistEnCode(id, entity.getEnCode())) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        systemService.update(id, entity);
        // 如果禁用了系统，则需要将系统
        List<OnlineUserModel> onlineUserList = OnlineUserProvider.getOnlineUserList();
        List<UserEntity> userName = userService.getUserName(onlineUserList.stream().map(OnlineUserModel::getUserId).collect(Collectors.toList()));
        userName.forEach(t -> {
            if (systemEntity.getId().equals(t.getSystemId())) {
                for (OnlineUserModel item : onlineUserList) {
                    if (item.getUserId().equals(t.getId()) && item.getWebSocket().isOpen()) {
                        Map<String, String> map = new HashMap<>(1);
                        map.put("method", "refresh");
                        if (StringUtil.isNotEmpty(userProvider.get().getTenantId())) {
                            if (userProvider.get().getTenantId().equals(item.getTenantId())) {
                                item.getWebSocket().getAsyncRemote().sendText(JsonUtil.getObjectToString(map));
                            }
                        } else {
                            item.getWebSocket().getAsyncRemote().sendText(JsonUtil.getObjectToString(map));
                        }
                    }
                }
            }
        });
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 删除系统
     *
     * @param id 主键
     * @return ignore
     */
    @Operation(summary = "删除系统")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @SaCheckPermission("system.menu")
    @DeleteMapping("/{id}")
    public ActionResult<String> delete(@PathVariable("id") String id) {
        SystemEntity entity = systemService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail(MsgCode.FA003.get());
        }
        if (entity.getIsMain() == 1) {
            return ActionResult.fail("主系统不允许删除");
        }
        // 系统绑定审批常用语时不允许被删除
        if(commonWordsService.existSystem(id)){
            return ActionResult.fail("系统在审批常用中被使用，不允许删除");
        }else {
            systemService.delete(id);
        }
        return ActionResult.success(MsgCode.SU003.get());
    }

}
